import axios, {
  type InternalAxiosRequestConfig,
  type AxiosResponse,
} from "axios";
import { getToken } from "@/utils/tokenTools";
import { useUserStoreHook } from "@/store/module/useUserStore";
import { message, Modal } from "ant-design-vue";

const axiosInstance = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 10000,
  headers: {},
});

// 添加请求拦截器
axiosInstance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = getToken();

    if (token) {
      config.headers.Authorization = token;
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => {
    // 二进制数据直接返回
    if (
      response.request.responseType === "blob" ||
      response.request.responseType === "arraybuffer"
    ) {
      return response.data;
    }
    const { code, data, msg } = response.data;
    if (code === 200) {
      message.success(msg);
      return data;
    }
    message.error(msg || "系统出错");
    return Promise.reject(new Error(msg || "Error"));
  },
  (error) => {
    const status = error.response.status;
    const userStore = useUserStoreHook();

    switch (status) {
      case 400:
        error.message = "请求错误";
        break;
      case 401:
        error.message = "没有权限访问";
        break;
      case 403:
        error.message = "拒绝访问";
        break;
      case 404:
        error.message = "访问地址出错";
        break;
      case 408:
        error.message = "请求超时";
        break;
      case 500:
        error.message = "服务器内部错误";
        break;
      case 501:
        error.message = "服务未实现";
        break;
      case 502:
        error.message = "网关错误";
        break;
      case 503:
        error.message = "服务不可用";
        break;
      case 504:
        error.message = "网关超时";
        break;
      case 505:
        error.message = "HTTP 版本不受支持";
        break;
      default:
        break;
    }
    message.error(error.message);

    if (status === 401) {
      Modal.confirm({
        title: "当前页面已失效，请重新登录",
        onOk() {
          userStore.logout();
        },
        onCancel() {
          console.log("Cancel");
        },
      });
    }

    return Promise.reject(error);
  }
);

export default axiosInstance;
